<?php
require("/home/ryerp_api/qm/DBPDO2.php");
require("/home/ryerp_api/qm/alipub/TopSdk.php");
//在奇门中创建订单
//author wzb
//2019.04.03
class Greatorder{
  public $appSecret = '6338e7a19f2bc4be1ec57480888474cb';
  public $appkey = '24839886';
  public $target_app_key = '24839886';
  public $Version = '2.0';
//  public $url = 'http://wr3esii1yq.api.taobao.com/router/qm?';
  public $url = 'http://ruiyuhair.cn/aliexpress/Greatorder?';
  public $format = 'json';
  public $sign_method = 'md5';
  public $data;
  public $mysql;
  public function __construct(){
      $this->mysql = new \DBPDO2();
  }
/**
 * [getorderdata 获取本地订单]
 * @return [type] [description]
 */
  public function getorderdata(){
    $sql_order = "select * from dlz_order_info where post_status='0' and payment_last_trans_id != '' and issendqm='1'";
    $row_orders = $this->mysql->doSql($sql_order);
    return $row_orders;
  }
/**
 * [getchildinfo 获取子订单信息]
 * @return [type] [description]
 */
  public function getchildinfo($orderId=''){
    $sql_product = "select * from dlz_post_orderinfo where increment_id='$orderId'";  
    $query_product = $this->mysql->doSql($sql_product);
    return $query_product;
  }
/**
 * [getbuyerinfo 买家信息]
 * @return [type] [description]
 */
public function getbuyerinfo($orderId=''){
    $query_buyer = $this->mysql->where("increment_id='$orderId'")->select('dlz_shipping_info',$type='single');
    return $query_buyer;
}

  public function optionorderdata(){
    $row_orders = $this->getorderdata();
    foreach ($row_orders as $key => $row_order) {
            $postarrary = array();
            $shopId = "mall00".$row_order['store_id'];
            $orderId = $row_order['increment_id'];
            echo " ***************$shopId***$orderId****************\n";
            $status = $row_order['status'];//订单状态 WAIT_SELLER_SEND_GOODS WAIT_BUYER_ACCEPT_GOODS FINISH
            if($status == "complete"){
                $orderStatus = "FINISH";
            }elseif($status == "processing") {
                 $orderStatus = "WAIT_SELLER_SEND_GOODS";//WAIT_BUYER_ACCEPT_GOODS
            }elseif($status == "Closed"){
                 $orderStatus = "FINISH_pay_closed";
            }else{
              continue;
            }
            
            $base_total_paid_str = $row_order['base_total_paid'];//pay_success pay_closed 付款状态
            $base_total_paid = Number_format($base_total_paid_str, 2, '.','');
            $Netamount = Number_format($row_order['Net_amount'], 2, '.','');
            if(empty($base_total_paid_str)){
                  $loanStatus = "PAY_CLOSED";
            }else{
                  $loanStatus = "PAY_SUCCESS";
            }          
            $created_at = $row_order['created_at'];
            //独立站后台使用的是世界时间，再次转换为太平洋时间
            $created_at = date('Y-m-d H:i:s',strtotime('-8 hour',strtotime($created_at)));            
            $gmtCreate = $created_at;
            $gmtModified = $created_at;
            $gmtPaySuccess = $gmtCreate;
            $base_grand_total_str = $row_order['base_grand_total'];
            $base_grand_total = Number_format($base_grand_total_str, 2, '.','');
            $order_currency_code = $row_order['order_currency_code'];
            $base_shipping_amount_str = $row_order['base_shipping_amount'];
            $base_shipping_amount = Number_format($base_shipping_amount_str, 2, '.','');
            $payment_method = $row_order['payment_method'];//WU PP WeChatPay Alipay BankTransfer  
            if ($payment_method == 'paypal_express') {
              $payment_method = 'PP';
            }
            $billNo = $row_order['payment_last_trans_id'];
          //订单基础信息
          $postarrary['requestEntity']['shopId'] = "$shopId";
          $postarrary['requestEntity']['orderId'] = "$orderId";
          $postarrary['requestEntity']['orderStatus'] = "$orderStatus";
          $postarrary['requestEntity']['loanStatus'] = "$loanStatus";
          $postarrary['requestEntity']['gmtCreate'] = "$gmtCreate";
          $postarrary['requestEntity']['gmtModified'] = "$gmtModified";
          $postarrary['requestEntity']['gmtPaySuccess'] = "$gmtPaySuccess";
          $postarrary['requestEntity']['phone'] = "false";
          $postarrary['requestEntity']['sellerOperatorLoginId'] = "$shopId";
          //获取子订单信息
          $rowproduct = $this->getchildinfo($orderId);
         if (count($rowproduct) == 0) {
          echo "产品不存在\n";
          $up_status = "update dlz_order_info set post_status='7' where increment_id='$orderId'";//post成功 修改状态
          $this->mysql->doSql($up_status);          
           continue;
         }
          $num = 0;//循环键值
          //遍历子订单信息
          foreach ($rowproduct as $row_product) {
              $id = $row_product['child_id'];
              $productId = $row_product['product_id'];
              $category = $row_product['category'];
              $color = $row_product['color'];
              $grade = $row_product['grade'];
              $style_str = $row_product['texture'];//
              //处理部分花型
              if(strpos("$style_str",'Body') !== false){
                  $style = "Body";
              }else if(strpos("$style_str",'Deep') !== false){
                  $style = "Deep";
              }else if (strpos("$style_str",'Curly') !== false){
                  $style = "Kinky Curly";
              //}else if (strpos("$style_str",'Straight') !== false){
              }else if (strpos("$style_str",'Straight') !== false && strpos("$style_str",'Hair') !== false){
                  $style = "Straight";
              }else{
                  $style = $style_str;
              }
              // 修正 ，有些 国家带 hair  有些不带，并且修正一些拼写错误  /首字母大写
              $humanHairType_str = ucfirst(trim($row_product['type_country']));
              if(strpos("$humanHairType_str",'Hair') !== false){
                 $humanHairType = $humanHairType_str;
              }else{
                 $humanHairType = $humanHairType_str.' '.'Hair';
              }
              if(strpos("$humanHairType",'Malaysian') !== false){
                $humanHairType = "Malaysia Hair";// 与速卖通平台保持一致
              }
              $size = $row_product['inch'].'inch';//尺寸与系统一致
              $type = $row_product['type'];//待定Lace Closure Silk Base Closure Lace Frontal Silk Base Frontal
              $hairDesign = $row_product['hairDesign'];
              $capSize_str = $row_product['capSize'];
              //修正发冒大小
              if(strpos("$capSize_str",'Small') !== false){
                  $capSize = "Small";
              }else if(strpos("$capSize_str",'Medium') !== false){
                  $capSize = "Medium";
              }else if(strpos("$capSize_str",'Large') !== false){
                  $capSize = "Large";
              }else if(strpos("$capSize_str",'Average') !== false){
                  $capSize = "Average Size";
              }else{
                  $capSize = $capSize_str;
              }
              $laceWigType = $row_product['laceWigType'];
              $density_str = $row_product['density'];//不接收 % 号。报错 400
              $density = str_replace('%','',$density_str);
              $lacesize = $row_product['laceSize'];
              $lotNum = $row_product['lotNum'];
              $productCount = $row_product['productCount'];
              //$currencyCode = $row_product['currencyCode'];
              $amount = $row_product['amount'];
              //产品信息
              $child_amount = Number_format(0, 2, '.','');
              $postarrary['requestEntity']['childOrderList'][$num] = array(
                              'id' => "$id",
                              'productId' => "$productId",
                              'productOwnerMemberId' => "$shopId",
                              'category' => "$category",
                              'color' => "$color",
                              'grade' => "$grade",
                              'humanHairType' => "$humanHairType",
                              'size' => "$size",
                              'style' => "$style",
                              'type' => "$type",
                              'hairDesign' => "$hairDesign",
                              'capSize' => "$capSize",
                              'laceWigType' => "$laceWigType",
                              'density' => "$density",
                              'lacesize' => "$lacesize",
                              'lotNum' => "$lotNum",
                              'productCount' => "$productCount",
                              'initAmt' => array(
                                'amount' => "$child_amount",
                                'currencyCode' => "$order_currency_code"
                                )
              ); 
              $num++;
    } //产品循环结束  
            //买家信息
            $row_buyer = $this->getbuyerinfo($orderId);
            //英国不被识别，需转下。
            //自动修正快递公司            
            $country_str = $row_buyer['country_id'];
            if($country_str == 'GB'){
                $country = 'UK';//英国不被识别，需转下
                $ShipperCode = 'GES';
            }elseif($country_str == 'US'){
                $ShipperCode = 'FEDEX';
                $country = $country_str;    
            }else{
                $ShipperCode = 'DHL';
                $country = $country_str;
            }
            $postarrary['requestEntity']['expresscompany'] = "$ShipperCode";
            $email = $row_buyer['email'];
            $loginId = $row_buyer['entity_id'];
            $firstName = $row_buyer['firstname'];
            $lastName = $row_buyer['lastname'];
            $address_str = $row_buyer['shipping_street'];
            $address_str = str_replace('__', '', $address_str);
            if(strlen($address_str) <= 180){
              $address = $address_str;
            }else{
              $address = '';
            }
            $zip = $row_buyer['postcode'];
            $mobileNo_str = $row_buyer['telephone'];
            if(!empty($mobileNo_str)){
                $mobileNo = $this->findNum($str="$mobileNo_str");//调用正则 识别号码
            }
            $detailAddress = $row_buyer['shipping_street'];
            $city = $row_buyer['city'];
            $province = $row_buyer['region'];
            $postarrary['requestEntity']['buyerInfo'] = array(
                                'country' => "$country",
                                'email' => "$email",
                                'loginId' => "$loginId",
                                'firstName' => "$firstName",
                                'lastName' => "$lastName"

                    );
            $buyerSignerFullname = $firstName.' '.$lastName;
            $postarrary['requestEntity']['buyerLoginId'] = "$loginId";
            $postarrary['requestEntity']['buyerSignerFullname'] = "$buyerSignerFullname";
            $postarrary['requestEntity']['orderAmount'] = array(
                                'amount' => "$base_grand_total",
                                'currencyCode' => "$order_currency_code"
                    );
            $postarrary['requestEntity']['logisticsAmount'] = array(
                                'amount' => "$base_shipping_amount",
                                'currencyCode' => "$order_currency_code"

                    );
            $postarrary['requestEntity']['realloanAmount'] = array(
                                        'amount' => "$Netamount",
                                        'currencyCode' => "$order_currency_code"
                    );
            $postarrary['requestEntity']['paymentType'] = "$payment_method";
            $postarrary['requestEntity']['billNo'] = "$billNo";           
            $postarrary['requestEntity']['receiptAddress'] = array(
                                'address' => "$address",
                                'address2' => '',
                                'city' => "$city",
                                'contactPerson' => "$buyerSignerFullname",
                                'country' => "$country",
                                'detailAddress' => "$address",
                                'faxArea' => '',
                                'faxCountry' => '',
                                'faxNumber' => '',
                                'mobileNo' => " $mobileNo",
                                'phoneArea' => '',
                                'province' => "$province",
                                'zip' => "$zip"
                  );
              $postarrary['requestEntity']['memo1']='';
      $this->optionReturnData($postarrary,$orderId);
     // exit;
  }
}
/**
 * [postToQm 推送到奇门]
 * @param  string $postarrary [description]
 * @return [type]             [description]
 */
public function postToQm($postarrary=''){
    $json = json_encode($postarrary);
    /*$json = str_ireplace("#", "\jing", $json);
    $json = str_ireplace("'", "\'", $json);
    $json = str_ireplace("\n", "", $json);
    $json = str_ireplace("%", "\bai", $json);*/
    
    $this->data = array(
                'app_key' => $this->appkey,
                'target_app_key' => $this->target_app_key,
                'v' => $this->Version,
                'format' => $this->format,
                "timestamp" => date('Y-m-d H:i:s'),
                'sign_method' => $this->sign_method
    );
    $this->data['requestEntity'] = $json;   
    $this->data['method'] = 'aliexpress.qmorder.greatorder';
    $this->data['sign'] = $this->getsingnature($this->data);
    $resarrary = $this->Getmethon($this->data);
    return   $resarrary;
}

  /**
     * *
     * @param  获取签名
     * @return post_data
    */
  public function getsingnature($datas) {
        ksort($datas);
        $aliParams = '';
        foreach ($datas as $key => $val) {
            $aliParams .= $key . $val;
        }
        $outputStr = strtoupper(md5($this->appSecret.$aliParams.$this->appSecret));
        return  $outputStr;
  }

  /**
   * [Getmethon POST GET curl]
   * @param [type] $data        [数据]
   * @param string $requestType [类型]
   */
  public function Getmethon($data,$requestType = 'get'){
          $curl=curl_init();
          print_r($data);
          
          //设置超时
          $url = $this->url.http_build_query($data);
          curl_setopt($curl, CURLOPT_TIMEOUT, 60);
          curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
          curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
          curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
          curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
          curl_setopt($curl,CURLOPT_HEADER,FALSE); 
/*          curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                  'Content-Type=application/json; charset=utf-8'
              ));*/
          curl_setopt($curl,CURLOPT_URL,$url);
          if (strtolower($requestType) == 'post') {
              curl_setopt ( $curl, CURLOPT_POST, 1 );
              curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data);
          }
          print_r($url);
          $result = curl_exec($curl);
          print_r($result);
          $resarrary = json_decode($result,true);
          curl_close($curl);
          return $resarrary;
  }

// 只匹配数字
public function findNum($str=''){
        $str=trim($str);
        if(empty($str)){return '';}
        $temp=array('1','2','3','4','5','6','7','8','9','0');
        $result='';
        for($i=0;$i<strlen($str);$i++){
            if(in_array($str[$i],$temp)){
                $result.=$str[$i];
            }
        }
        return $result;
    }

/**
 * [optionReturnData 处理返回值信息]
 * @param  string $postarrary [description]
 * @return [type]             [description]
 */
  public function optionReturnData($postarrary='',$orderId=''){
    $return = $this->postToQm($postarrary);
    $ret_code1 = isset($return['response']['ret_code'])?$return['response']['ret_code']:'';
    $ret_code2 = isset($return['ret_code'])?$return['ret_code']:'';
    if (empty($ret_code1)) {
      $ret_code = $ret_code2;
    }else if (empty($ret_code2)) {
      $ret_code = $ret_code1;
    }else{
      $ret_code = '';
    }
    if ($ret_code == '1000' || $ret_code == '1005') {
      //成功
      $insert_status = "update dlz_order_info set post_status='1' where increment_id='$orderId'";//post成功 修改状态
      $this->mysql->doSql($insert_status);
      echo " ----sucess----\n";    
    }else{
      echo " ----error----\n";
    }
  }

}

$Greatorder = new Greatorder();
$Greatorder->optionorderdata();
//{"response":{"flag":"failure","code":15,"message":"Remote service error","sub_code":"http-service-status-error","sub_message":"http status error:500","request_id":"4jk31dp75syv"}}
//代表服务端 代码  有错
